#pragma once

#include <iostream>
#include <string>
#include <sys/poll.h>
#include <cerrno>
#include "Sock.hpp"
#include "Err.hpp"
#include "log.hpp"

const static int gport = 8080;
typedef pollfd type_t;
static const int N = 4096;
const short defaultevent = 0;

class PollServer
{
public:
    PollServer(uint16_t port = gport) : _port(port), _fdarray(nullptr), len(N)
    {
    }
    ~PollServer()
    {
        _listensock.Close();
        if (_fdarray)
            delete[] _fdarray;
    }

    void InitServer()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listhen();
        _fdarray = new type_t[len];
        for (int i = 0; i < len; i++)
        {
            _fdarray[i].fd = defaultfd;
            _fdarray[i].events = defaultevent;
        }
    }

    void Accepter()
    {
        std::cout << "新连接到来" << std::endl;
        // 开始accept
        std::string clientip;
        uint16_t clientport;
        int sock = _listensock.Accept(&clientip, &clientport);
        if (sock < 0)
            return;

        logmessage(DEBUG, "[%s:%d] sock: %d", clientip.c_str(), clientport, sock);

        // 把获得的fd添加进数组
        int i = 0;
        for (i = 1; i < N; i++)
        {
            if (_fdarray[i].fd == defaultfd)
                break;
        }
        if (i >= len)
        {
            // // 1.关闭
            // close(sock);
            // logmessage(WARNING, "sockfd array is full");

            // 2.扩容
            int newlen = len * 2;
            type_t *newfdarray = new type_t[len];
            for (int j = 0; j < len; j++)
            {
                newfdarray[j] = _fdarray[j];
            }
            newfdarray[len].fd = sock;
            _fdarray[i].events = POLLIN;
            delete[] _fdarray;
            _fdarray = newfdarray;
            len = newlen;
        }
        else
        {
            _fdarray[i].fd = sock;
            _fdarray[i].events = POLLIN;
        }
    }

    void Handerevent()
    {
        for (int i = 0; i < len; i++)
        {
            int fd = _fdarray[i].fd;
            short revent = _fdarray[i].revents;
            if (fd == defaultfd)
                continue;

            if (fd == _listensock.Fd() && revent & POLLIN) // 处理新连接事件
            {
                Accepter();
            }
            else if (revent & POLLIN) // 处理读事件就绪
            {
                char buffer[1024];
                ssize_t s = recv(fd, buffer, sizeof(buffer), 0);
                if (s > 0)
                {
                    buffer[s - 1] = '\0';
                    std::cout << "client# " << buffer << std::endl;

                    // 将数据发送回去
                    std::string echo = buffer;
                    echo += " [select server echo]";
                    send(fd, echo.c_str(), echo.size(), 0);
                }
                else
                {
                    if (s == 0)
                    {
                        logmessage(INFO, "client quit...");
                    }
                    else
                    {
                        logmessage(WARNING, "recv error,client quit...");
                    }
                    close(fd);
                    _fdarray[i].fd = defaultfd;
                    _fdarray[i].events = defaultevent;
                    _fdarray[i].revents = defaultevent;
                }
            }
        }
    }

    void start()
    {
        // struct timeval timeout = {2, 0};
        _fdarray[0].fd = _listensock.Fd();
        _fdarray[0].events = POLLIN;
        while (true)
        {
            int timeout = -1;
            int n = poll(_fdarray, N, timeout);

            switch (n)
            {
            case 0:
                logmessage(DEBUG, "time out...");
                break;
            case -1:
                logmessage(WARNING, "select error, %s", strerror(errno));
                break;
            default:
                logmessage(DEBUG, "有文件已就绪: %d", n);
                Handerevent();
                break;
            }
        }
    }

private:
    uint16_t _port;
    Sock _listensock;
    type_t *_fdarray;
    int len;
};